﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Linq.Expressions;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Html;

namespace MIMSWeb.HtmlHelpers
{
    public static class EnumDropDownHelpers
    {
        public static MvcHtmlString EnumDropDownListFor<TModel, TEnum>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TEnum>> expression, Object htmlAttributes)
        {
            //get the metadata from the model
            ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
            //get the type information
            IEnumerable<TEnum> values = Enum.GetValues(typeof(TEnum)).Cast<TEnum>();
            //create list items using LINQ
            IEnumerable<SelectListItem> items = values.Select(value => new SelectListItem
            {
                //Text = ((DisplayAttribute)value.GetType().GetField(value.ToString()).GetCustomAttributes(typeof(DisplayAttribute), false).First()).GetName(),
                Text = value.ToString(),
                Value = value.ToString(),
                Selected = value.Equals(metadata.Model)
            });

            return htmlHelper.DropDownListFor(expression, items, htmlAttributes);
        }
    }
}